//
//  ForithmAnimation.m
//  AnimationDemo
//
//  Created by Jiaozl 2018 on 2018/9/13.
//  Copyright © 2018年 Jiaozl. All rights reserved.
//
// 渐显动画：新页面从无到有逐渐显现
//

#import "GraduallyShowAnimation.h"

@implementation GraduallyShowAnimation

/// 转场动画时间
- (NSTimeInterval)transitionDuration:(nullable id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.8;
}

- (void)animateTransition:(nonnull id<UIViewControllerContextTransitioning>)transitionContext
{
    // 设置view的渐显/渐隐
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    fromView.alpha = 1.0;
    toView.alpha = .0;
    
    // 在present和，dismiss时，必须将toview添加到containerView中
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toView];
    
    // 获取执行时长
    NSTimeInterval transitionDuration = [self transitionDuration:transitionContext];
    [UIView animateWithDuration:transitionDuration animations:^{
        fromView.alpha = .0;
        toView.alpha = 1.0;
    } completion:^(BOOL finished) {
        // transitionWasCancelled 这个方法判断转场是否已经取消了，下面的completeTransition设置转场完成
        // 动画结束后一定要调用completeTransition方法
        // 通过transitionWasCancelled()方法来获取转场的状态，使用completeTransition:来完成或取消转场。
        BOOL wasCancelled = [transitionContext transitionWasCancelled];
        [transitionContext completeTransition:!wasCancelled];
    }];
}

@end
